package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public Result selectTypeList() {
        //查询redis缓存是否有数据
        List<ShopType> shopType = new ArrayList();
        if (!stringRedisTemplate.opsForHash().entries("shop:type:" + "1").isEmpty()) {
            for (int i = 0; i < 10; i++) {
                Map<Object, Object> shoptypeDTO = stringRedisTemplate.opsForHash().entries("shop:type:" + i);
                ShopType shopType1 = BeanUtil.fillBeanWithMap(shoptypeDTO, new ShopType(), false);
                shopType.add(shopType1);
            }
        }

        //如果有，直接返回
        if (shopType.size()!=0) {
            return Result.ok(shopType);
        }
        //如果没有，查询数据库
        List<ShopType> typeList = query().orderByAsc("sort").list();
        if ((typeList == null) || (typeList.size() == 0)) {
            return Result.fail("没有数据");
        }

        for (int i = 0; i < typeList.size(); i++) {
            Map<String, Object> shopTypeMap = BeanUtil.beanToMap(typeList.get(i),new HashMap<>(),
                    CopyOptions.create()
                            .setIgnoreNullValue(true)
                            .setFieldValueEditor((fieldName,fieldValue)->fieldValue.toString()));
            //将数据存入redis数据库
            stringRedisTemplate.opsForHash().putAll("shop:type:"+i,shopTypeMap);
        }

        return Result.ok(typeList);
    }
}
